package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.properties.JwtProperties;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import com.sky.utils.EmployeeHolder;
import com.sky.utils.JwtUtil;
import com.sky.utils.Regex;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private HttpServletRequest request;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // 对前端传过来的明文密码进行md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public Result save(EmployeeDTO employeeDTO) {
        //1.判断账号密码是否符合条件，不符合返回
        if (!employeeDTO.getUsername().matches(Regex.USERNAME_REGEX)) {
            return Result.error("账号输入不符，请输入3-20个字符");
        }
        if (!employeeDTO.getName().matches(Regex.NAME_REGEX)) {
            return Result.error("请输入正确格式姓名");
        }
        if (!employeeDTO.getPhone().matches(Regex.PHONE_REGEX)) {
            return Result.error("请输入正确手机号");
        }
        if (!employeeDTO.getIdNumber().matches(Regex.ID_REGEX)) {
            return Result.error("身份证号不正确");
        }
//        //2.账号是否重复：
//        if (employeeMapper.queryEmployeeByUsername(employeeDTO.getUsername()) != null) {
//            return Result.error("该用户已存在");
//        }
        //3.符合插入数据库
        String token = request.getHeader("token");
        Long createUserId = BaseContext.getCurrentId();
        System.out.println("createUserId:" + createUserId);
        Employee employee = Employee.builder()
                .password(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()))
                .status(StatusConstant.ENABLE).build();
        BeanUtils.copyProperties(employeeDTO, employee);

        employeeMapper.saveEmployee(employee);

        //4.返回
        return Result.success();
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public Result pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
        //select * from employee limit 0,10;
        //开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        long total = page.getTotal();
        List<Employee> records = page.getResult();

        return Result.success(new PageResult(total, records));
    }

    @Override
    public Result updateEmployeeStatus(Long empId, Integer status) {
        //只修改一个属性的方法
        employeeMapper.updateEmployeeStatus(empId, status);
        //修改所有不为空的方法，增强拓展性
//        Employee employee = Employee.builder()
//                .id(empId)
//                .status(status).build();
//        employeeMapper.updateEmployee(employee);
        return Result.success();
    }

    @Override
    public Result queryEmoloyeeById(Long empId) {
        return Result.success(employeeMapper.queryEmployeeById(empId));
    }

    @Override
    public Result updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = Employee.builder()
                .id(employeeDTO.getId())
                .idNumber(employeeDTO.getIdNumber())
                .name(employeeDTO.getName())
                .phone(employeeDTO.getPhone())
                .sex(employeeDTO.getSex())
                .username(employeeDTO.getUsername()).build();
        employeeMapper.updateEmployee(employee);
        return Result.success();
    }


}